package org.bjf.modules.user.web.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.binary.Base64;
import org.bjf.exception.CommMsgCode;
import org.bjf.exception.ServiceException;
import org.bjf.utils.ExceptionAssert;
import org.bjf.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("security")
public class SecurityController {

    @Autowired
    private DefaultKaptcha kaptcha;

    @RequestMapping("kaptcha")
    public Object kaptcha() {

        String imgCode = kaptcha.createText();

        BufferedImage image = kaptcha.createImage(imgCode);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpg", bos);
            String imgStr = Base64.encodeBase64String(bos.toByteArray());
            String token = TokenUtil.genJwtImgToken(imgCode, 100);

            return ImmutableMap.of("imgToken", token, "imgCode", imgStr);
        } catch (IOException e) {
            throw new ServiceException("生成验证码失败");
        }
    }

    @RequestMapping("kaptcha/valid")
    public void imgValid(String imgToken, String imgCode) {
        Claims claims = null;
        try {
            claims = TokenUtil.parseJwtToken(imgToken);
        } catch (ServiceException e) {
            throw new ServiceException(CommMsgCode.SECURITY_ERROR, "验证码已过期");
        }

        String code = claims.get("imgCode", String.class);
        ExceptionAssert.isTrue(imgCode.equalsIgnoreCase(code), "验证码不正确");
    }
}
